User Authentication in Django

Manish Patel

Aug 25, 2023

Django authentication (login, logout, and signup)

Key Concepts

  1. Authentication System: Django provides a built-in authentication system that allows you to manage user authentication and authorization. It includes user models, views, forms, and templates for handling authentication-related tasks.

  2. User Model: The User model in django.contrib.auth.models represents user accounts. It includes fields like username, email, and password for user authentication.

  3. Login: Login is the process of verifying a user’s identity using their credentials (usually a username and password). Django provides a LoginView for handling user login. It involves checking the provided credentials against the stored credentials in the database.

  4. Logout: Logout is the process of ending a user’s session. Django provides a LogoutView for handling user logout. It involves clearing the session data and redirecting the user to a specified URL.

  5. Signup/Register: Signup or registration is the process of allowing users to create new accounts. Django doesn’t provide a built-in view for signup, but you can use the UserCreationForm from django.contrib.auth.forms to create a registration form. Upon successful registration, users are typically logged in automatically.

  6. Sessions and Cookies: Django uses sessions and cookies to manage user authentication. A session is a way to store user-related data across multiple requests. Cookies are used to store session IDs on the user’s browser.

Key Concepts

  1. Middleware: Django’s authentication system relies on middleware to handle user authentication. The AuthenticationMiddleware authenticates users based on the session and populates the request.user object with user information.

  2. Templates and Views: Django provides built-in templates and views for authentication, including login and logout. You can customize these templates and views to match your project’s design and requirements.

  3. URLs and URL Patterns: URLs are used to route requests to the appropriate views. You need to define URL patterns for login, logout, and other authentication-related actions in your urls.py file.

  4. Signals: Django’s authentication system uses signals to perform actions when specific events occur. For example, you can use signals to perform tasks after a user logs in or logs out.

  5. Authentication Decorators: Decorators like @login_required can be applied to views to restrict access to authenticated users. Users who aren’t logged in are redirected to the login page.

  6. Customization: You can customize the authentication system to fit your project’s requirements. This includes using custom user models, creating custom authentication backends, and extending built-in views and forms.

Django user authentication, including Signup, login and logout functionality.

Step 1: Create the Django Project and App

  • Open your terminal and run the following commands:
# Create a new Django project
django-admin startproject AuthDemoProject

# Change into the project directory
cd AuthDemoProject

# Create a new app named "accounts"
python manage.py startapp accounts
  • Register app in the settings

Step 2: Configure URLs

In AuthDemoProject/urls.py, include the app’s URLs:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('accounts.urls')),
]

Step 3: Create Views

In accounts/views.py, you don’t need to create custom login and logout views because Django provides built-in views for authentication:

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, logout, authenticate
from django.shortcuts import render, redirect
from django.contrib import messages

def dashboard(request):
    return render(request, 'accounts/dashboard.html')

def user_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            messages.success(request, 'Login successful.')
            return redirect('dashboard')
        else:
            messages.error(request, 'Invalid login credentials.')
    return render(request, 'accounts/login.html')


def custom_logout(request):
    logout(request)
    return render(request, 'accounts/logout.html')

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, 'Signup successful. Welcome!')
            return redirect('dashboard')
    else:
        form = UserCreationForm()
    return render(request, 'accounts/signup.html', {'form': form})
  • Add in settings the following -
    LOGIN_REDIRECT_URL = ‘dashboard’ # Replace ‘dashboard’ with your desired URL name

Step 4: Create Templates

Inside the accounts app directory, create a templates/accounts directory. In this directory, create the following template.

accounts/signup.html -


<!DOCTYPE html>
<html>
<head>
    <title>Signup</title>
</head>
<body>
    <h1>Signup</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Signup</button>
    </form>
</body>
</html>

Dashboard html

accounts/dashboard.html:

<!DOCTYPE html>
<html>
<head>
    <title>User Dashboard</title>
</head>
<body>
    <h1>User Dashboard</h1>
    {% if user.is_authenticated %}
        <p>Welcome, {{ user.username }}!</p>
        <a href="{% url 'logout' %}">Logout</a>
    {% else %}
        <p>You are not logged in.</p>
        <a href="{% url 'login' %}">Login</a>
    {% endif %}
</body>
</html>

Login template

accounts/login.html:

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <form method="post">
        {% csrf_token %}
        <label for="username">Username:</label>
        <input type="text" name="username" required><br>
        <label for="password">Password:</label>
        <input type="password" name="password" required><br>
        <button type="submit">Login</button>
    </form>
</body>
</html>

Logout template

accounts/logout.html:

<!DOCTYPE html>
<html>
<head>
    <title>Logout</title>
</head>
<body>
    <h1>Logout</h1>
    <p>You have been logged out successfully.</p>
    <a href="{% url 'login' %}">Back to Login</a>
</body>
</html>

Step 5: Create URLs

In the accounts app directory, create a urls.py file:

from django.urls import path
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
    path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
    path('logout/', views.custom_logout, name='logout'),
    path('dashboard/', views.dashboard, name='dashboard'),
    path('signup/', views.signup, name='signup'),  # New URL pattern
]

Step 6: Run Migrations

python manage.py makemigrations
python manage.py migrate

Step 7: Run the Development Server

Run the development server:

python manage.py runserver

Step 7: Access the Pages

Visit the following URLs in your browser:

  • Dashboard: http://127.0.0.1:8000/accounts/dashboard/
  • Login: http://127.0.0.1:8000/accounts/login/
  • Signup: http://127.0.0.1:8000/accounts/signup/
  • Logout: http://127.0.0.1:8000/accounts/logout/